import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart';

enum FlutterActionType {
  appTestMethod,
  initSdk,
  sendData
}
class FlutterActionModel {

  FlutterActionType type; //action 执行事件
  late String method;
  Map<String, dynamic>? params;

  FlutterActionModel({
    required this.type,
    this.params,
  }) {
    method = type.name;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {};
    data["action"] = method;

    ///默认是自己的方法名字   下面可进行修改  根据类型判断
    switch (type) {
      case FlutterActionType.appTestMethod:
        {
        }
        break;
      case FlutterActionType.initSdk:
        {
        }
        break;
      case FlutterActionType.sendData:
        {
        }
        break;
    }
    if (params != null) {
      data.addAll(params ?? {});
    }
    return data;
  }
}

class YjHealthPlugin {
  // 工厂方法构造函数
  factory YjHealthPlugin() => _getInstance();

  // instance的getter方法，singletonManager.instance获取对象
  static YjHealthPlugin get instance => _getInstance();

  // 静态变量_instance，存储唯一对象
  static YjHealthPlugin? _instance;
  static const _channel = MethodChannel('yj_health_plugin'); //原生通讯

  static YJKtvEventChannel? _eventChannel; //事件通讯
  /// event传递给外部使用
  Function(String)? messageCallback;

  // 获取对象
  static YjHealthPlugin _getInstance() {
    if (_instance == null) {
      return _instance = YjHealthPlugin._internal();
    }
    return _instance!;
  }
  // VoidCallback? _globalListener;
  // 私有的自定义命名式构造方法，通过它实现一个类;
  // 子类不能继承internal
  // 不是关键字，可定义其他名字
  YjHealthPlugin._internal() {
    //初始化(设置一些默认的)...
    print("开始监听事件通讯");
    _eventChannel = YJKtvEventChannel(
            (message) => _onData(message), (Error error) => _error(error));
  }
  /// flutter 收到消息------------------------收
  void _onData(message) {
    try {
      print(message);
      if (messageCallback != null) {
        messageCallback!(message);
      }
    } catch (e) {
      print(e.toString());
    }
  }

  void _error(Error error) {
    print("监听数据出现了错误");
  }

  ///销毁事件
  void cancel() {
    _eventChannel?.cancel();
  }

  ///传值给iOS Android--------------------------发
  Future flutterSendEvent(
      {required FlutterActionModel flutterActionModel}) async {
    try {
      var result = await _channel.invokeMethod(
          flutterActionModel.method, {'data': flutterActionModel.toJson()});
      return result;
    } catch (e) {
      print(e);
      return Future.error("bugly error");
    }
  }

}


class YJKtvEventChannel {
  final EventChannel _channel = const EventChannel('yj_ktc_event');

  late StreamSubscription _streamSubscription;

  Function messageCallback = (String message) => {};
  Function errorCallback = (Error error) => {};

  YJKtvEventChannel(this.messageCallback, this.errorCallback) {
    _streamSubscription = _channel
        .receiveBroadcastStream()
        .listen(_onEvent, onError: _onToDartError);
  }

  void _onEvent(message) {
    // print("debug 信息流: $message");
    messageCallback(message);
  }

  void _onToDartError(error) {
    print(error);
    errorCallback(error);
  }

  void cancel() {
    _streamSubscription.cancel();
  }

  void pause() {
    _streamSubscription.pause();
  }

  bool isPaused() {
    return _streamSubscription.isPaused;
  }

  void resume() {
    //_streamSubscription 没停止也可以调用resume，内部做了安全处理
    _streamSubscription.resume();
  }
}
